﻿<%@ WebHandler Language="C#" Class="ContainerMoveOrRevokeDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;
/**
 * Description: 批次调度、批次撤销统计看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2024.10.29
 */

public class ContainerMoveOrRevokeDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询统计数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetails":
                        r = getDetails(jObject);//查看明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//明细导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询sql
    string getSearchSql(JObject obj)
    {
        string sql = @"
SELECT f.factoryname,cci.mfgordername,cci.containername,wfs.workflowstepname fromworkflowstepname,
       tws.workflowstepname toworkflowstepname,em.fullname operater,hml.txndate operatetime,mh.notes
FROM historymainline hml
LEFT JOIN workflowstep wfs ON wfs.workflowstepid = hml.workflowstepid
LEFT JOIN movehistory mh ON hml.historymainlineid = mh.historymainlineid
LEFT JOIN employee em ON em.employeeid = mh.reportemployeeid
INNER JOIN containercurrentinfo cci ON cci.containerid = hml.containerid
LEFT JOIN workflowstep tws ON tws.workflowstepid = mh.tostepid
INNER JOIN factory f ON f.factoryid = cci.originalfactoryid
WHERE hml.reversalstatus = 1 AND mh.notes IN ('MoveBack','MoveNon')";
        //操作时间
        if (obj["createdate"] != null && obj["createdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(obj["createdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND hml.txndate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND hml.txndate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //流水卡号
        if (obj["containername"] != null && obj["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", obj["containername"].ToString());
        }

        //分厂
        if (obj["factoryname"] != null && obj["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryname = '{0}'", obj["factoryname"].ToString());
        }

        //类型
        if (obj["operatetype"] != null)
        {
            string operatetype = obj["operatetype"].ToString();
            if (operatetype.IndexOf("调度") > -1)
            {
                sql += " AND mh.notes = 'MoveNon'";
            }
            if (operatetype.IndexOf("撤销") > -1)
            {
                sql += " AND mh.notes = 'MoveBack'";
            }
        }

        return sql;
    }

    //查询数据
    Result getData(JObject obj)
    {
        string sql = @"
SELECT t.factoryname,COUNT(1) operateqty,t.notes,
       SUM(DECODE(t.notes,'MoveNon',1,0)) MoveNonQty,
       SUM(DECODE(t.notes,'MoveBack',1,0)) MoveBackQty
FROM
(
    {0}
) t
GROUP BY t.factoryname,t.notes";
        sql = string.Format(sql, getSearchSql(obj));

        DataTable dt = dal.GetDataTable(sql);
        dt.Columns.Add("containercount", typeof(decimal));
        dt.Columns.Add("operaterate", typeof(decimal));

        //统计各分厂在制批次数
        sql = @"
SELECT f.factoryname,COUNT(cci.containerid) containercount
FROM containercurrentinfo cci
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
WHERE cci.isinstore = 0
GROUP BY f.factoryname";

        DataTable dtWipInfo = dal.GetDataTable(sql);

        foreach (DataRow dr in dt.Rows)
        {
            string filter = string.Format("factoryname = '{0}'", dr["factoryname"].ToString());
            DataRow[] list = dtWipInfo.Select(filter);
            if (list.Length > 0)
            {
                dr["containercount"] = list[0]["containercount"];
                dr["operaterate"] = Math.Round(Convert.ToDecimal(dr["operateqty"]) / Convert.ToDecimal(dr["containercount"]), 4) * 100;
            }
            else
            {
                dr["containercount"] = 0;
                dr["operaterate"] = 0;
            }
        }

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查看明细
    Result getDetails(JObject obj)
    {
        string sql = getSearchSql(obj);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)obj["currentPage"], (int)obj["pageSize"]);
        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        foreach (DataRow dr in dt.Rows)
        {
            if (dr["notes"].ToString() == "MoveBack")
            {
                dr["notes"] = "批次撤销";
            }
            else
            {
                dr["notes"] = "批次调度";
            }
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //明细导出
    void exportExcel(JObject obj)
    {
        string sql = getSearchSql(obj);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataRow dr in dtResult.Rows)
        {
            if (dr["notes"].ToString() == "MoveBack")
            {
                dr["notes"] = "批次撤销";
            }
            else
            {
                dr["notes"] = "批次调度";
            }
        }

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["containername"].Caption = "批次号";
        dtResult.Columns["fromworkflowstepname"].Caption = "操作前工序";
        dtResult.Columns["toworkflowstepname"].Caption = "操作后工序";
        dtResult.Columns["operater"].Caption = "操作人";
        dtResult.Columns["operatetime"].Caption = "操作时间";
        dtResult.Columns["notes"].Caption = "操作类型";

        ExportHelper.ExportExcel(dtResult, obj["title"].ToString() + "导出");
    }
}